/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import router from '@system.router';
import prompt from '@system.prompt';
//import socket from '@ohos.net.socket';
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility';

const titles = [
    {
        'name': 'All'
    },

];

const chatData = [
    {
        'title': '账号',
        'topMessage': '欢迎来到华为鸿蒙操作系统',
        'imgUrl': '/common/images/sessionPic/img_8.png',
        'readTime': '17:00',
        'unRead': '8',
    },
    {
        'title': '密码',
        'topMessage': '吃了没有?',
        'imgUrl': '我叫学习',
        'readTime': '17:00',
        'unRead': '4',
    },

];
const personData = {
    'name': '我叫学习',
    'personNum': '萌聊号:133213321',
    'imgUrl': '/common/images/sessionPic/img_7.png',
}

export default {
    data: {
        titleList: titles,
        chatList: chatData,
        person:personData,
        // 滑动拼图验证的图片列表
        swipeImgList: [
            '/common/images/swipePuzzle/test1.jpg',
            '/common/images/swipePuzzle/test2.jpg',
            '/common/images/swipePuzzle/test3.jpg',
            '/common/images/swipePuzzle/test4.jpg',
            '/common/images/swipePuzzle/test5.jpg',
            '/common/images/swipePuzzle/test6.jpg',
            '/common/images/swipePuzzle/test7.jpg',
            '/common/images/swipePuzzle/test8.jpg'
        ],
        // 旋转拼图验证的图片列表
        rotateImgList: [
            '/common/images/swipePuzzle/test1.jpg',
            '/common/images/swipePuzzle/test2.jpg',
            '/common/images/swipePuzzle/test3.jpg',
            '/common/images/swipePuzzle/test4.jpg',
            '/common/images/swipePuzzle/test5.jpg',
            '/common/images/swipePuzzle/test6.jpg',
            '/common/images/swipePuzzle/test7.jpg',
            '/common/images/swipePuzzle/test8.jpg'
        ],
        // 滑动拼图验证的参数
        swipePuzzleTestAttrs: {
            width: 300,
            height: 225,
            blockSize: 50
        },
        // 旋转拼图验证的参数
        rotatePuzzleTestAttrs: {
            width: 300,
            height: 225,
            radius: 100
        },
        title: "",
        username: "",
        password: "",
        checkState: false,
        rotateState:false,
        response:'',
        token:'123456',
        returnValue:'',
        path:"",
        addToken:"",
    },
    onInit() {
        this.title = this.$t('strings.title');
        //取token
       /* let storage = dataStorage.getStorageSync(this.path);
        console.log("this.path " + this.path);
        storage.putSync('startup','auto');
        storage.flushSync()
        let result = storage.getSync('startup','00')
        console.log("result " + result)*/
    },

    onCreate(){
        //libsocket自带的接收
//        this.$app.$def.mysocket.connect("192.168.30.12",7777);
//        console.info("Application onCreate");
    },
   /* onDestroy(){
        this.$app.$def.mysocket.close();
    },*/
    // 事件处理函数，在此处定义验证完成后的操作
    onResReceived(e) {
        prompt.showToast({
            message: "父组件得到结果:" + e.detail.result
        });
        this.rotateState = e.detail.result;
    },
    // 监听用户输入框中数据信息的变化
    change(e) {
        this.username = e.value;
        this.$app.$def.uid = this.username;
    },
    // 监听密码输入框中数据信息的变化
    change2(e) {
        this.password = e.value;
    },
    checkboxOnChange(e) {
        this.checkState = e.checked;
    },

    getToken(){
        //取token
        /*let storage = dataStorage.getStorageSync(this.path);
        console.log("this.path " + this.path);
        storage.putSync('startup','auto');
        storage.flushSync()
        let result = storage.getSync('startup','00')
        console.log("result " + result)*/
        var context = featureAbility.getContext()
        context.getFilesDir().then(v =>{
            dataStorage.getStorage(v + '/smart_build').then(it =>{
                let promise = it.get("token","default")
                promise.then((value) => {
                    console.info("The value of token is " + value)
                    this.addToken = value
                }).catch((err) => {
                    console.info("Get the value of token failed with err: " + err)
                })
            })
        })
    },

    /**
     * 点击输入框操作
     *
     * @param e
     * @return 点击输入框操作
     */
    enterkeyClick(e) {
        prompt.showToast({
            message: "enterkey clicked",
            duration: 3000,
        });
    },
    clickCustomType(str) {
        console.log(str)
    },
    clickCustomType3(str) {
        console.log(str)
        router.push({ // 页面跳转进入注册
            uri: "pages/login/register/register",
            params: this.username + "-" + this.password
        })
    },
    /*
     * 存token到storage
     */
    setStorage(){
        //test
        var context = featureAbility.getContext()
        /*var path = context.getFilesDir()
        let storage = dataStorage.getStorageSync(path);
        console.error("path：" + path)
        storage.putSync('startup','auto')
        storage.flushSync()
        setTimeout(() => {
            let result = storage.getSync('startup','00')
            console.error("result：" + result)
        }, 5000);*/
        //context
         context.getFilesDir().then(v =>{
             dataStorage.getStorage(v + '/smart_build').then(it =>{
                 console.info("context.getFilesDir successfully.it" + it)
                 console.error("====response.token====>" + this.token)
                 it.put('token', this.token)
                     .then(() =>{
                         console.info("保存token成功")
                         it.flush()
                         let result = it.getSync('token','00')
                         console.error("result：" + result)
                     }).catch((err) =>{
                     console.error("保存token失败：" + err)
                 })
             })
         }).catch((err) =>{
             console.error("context.getFilesDir failed with err：" + err)
         })
    },
    closePanel() {
        this.$element('simplepanel').close()
    },
    /**
     * 确认点击操作
     */
    checkClick(){
        //response的响应返回是否验证成功！！
        if(this.returnValue == 0 && this.rotateState == true){
            //token存入
            this.setStorage()
            prompt.showToast({
                message: '登录成功！',
                duration: 2000,
            });
            router.push({ // 页面跳转进入列表刷新
                uri: "pages/sessionList/sessionList",
            })
        }else{
            prompt.showToast({
                message: '登录失败！',
                duration: 2000,
            });
        }
    },
    /**
     * 登录点击操作
     */
    loginClick(e) {
        //        this.$element("input").showError({
        //            error: '请输入正确信息'
        //        });
//        this.setStorage()
        if (!this.checkState) {
            console.log('请阅读服务协议与隐私保护')
            return;
        }
        //弹出弹窗
        this.$element('simplepanel').show()
        //定义发送包的格式
        var obj = {requestType:1,uid:this.username,password:this.password,token:"2213",returnValue:111};
        //通过mySocket连接发送数据。使用callback方式作为异步方法。
        console.info("send1232131")
        this.$app.$def.loginSocket.send(JSON.stringify(obj))
        console.info("send23212314324")
        setTimeout(() => {
            // TODO response响应，包括验证结果yesIt、token字符串
            this.response = this.$app.$def.loginSocket.receive()
            var obj2 = JSON.stringify(this.response);
            console.log("sdasdatest21:" + obj2 );
            //solve one
            this.token = obj2.substring(69,217);
            this.returnValue = obj2.substring(236,237);
            console.log("sdasdatest24:" + this.token + " " + this.returnValue );

            //object方法
//            this.res = Object.values(this.response)[3]
//            console.log("receive321321:" + Object.values(response)[3] );
//            console.log("receive3213211:" + Object.keys(response)[3] );

        }, 5000);

        }

}



